package com.cn.kabalifemerchants.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;


import com.cn.kabalifemerchants.base.MyApplication;
import com.cn.kabalifemerchants.config.ProjectConfig;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by 晓林 on 2020/6/20.
 * function:
 */
public class BitmapUtil {
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 截某個View保存本地
     *
     * @param view view的id
     * @param name 图片的名
     * @return
     */
    public static Bitmap saveBitmap(Context context, View view, String name) {
//        measure方法的参数值都设为0即可
        view.measure(0, 0);
        //获取组件宽度
        int width = view.getMeasuredWidth();
        //获取组件高度
        int height = view.getMeasuredHeight();
        LoggerUtils.e("宽高：" + width + "xx" + height);
        //截取NestedScrollView
//        view.setDrawingCacheEnabled(true);
//        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
//                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
//        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//        Bitmap bm = Bitmap.createBitmap(view.getDrawingCache());
        Bitmap bm = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
//        canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        if (bm != null)
            LoggerUtils.e("截图成功");
        else LoggerUtils.e("截图失败");
        // 首先保存图片
//        File appDir = MyApplication.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File appDir = new File(MyApplication.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + ProjectConfig.DIR_IMG);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));

//        if (bm!=null)
//            RxToast.success("保存成功");
        return bm;
    }


    /**
     * 压缩图片
     *
     * @param bgimage
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        //matrix.postScale(scaleWidth, scaleHeight);//TODO 因为宽高不确定的因素,所以不缩放
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    /**
     * 截取指定View为图片
     *
     * @param view
     * @return
     * @throws Throwable
     */
    public static Bitmap captureView(View view) throws Throwable {
        LoggerUtils.e("宽高1草：" + view.getWidth() + "---" + view.getHeight());
        view.measure(0, 0);
        //获取组件的宽度
        int width = view.getMeasuredWidth();
        //获取组件的高度
        int height = view.getMeasuredHeight();
        LoggerUtils.e("宽高2草 ：" + width + "---" + height);
        Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        view.draw(new Canvas(bm));
        return bm;
    }
}

